<script setup lang="ts">
import * as echarts from 'echarts';
import type { EChartEventHandler } from 'my-web-core/interfaces';
import { onMounted, onUnmounted, ref, watch } from 'vue';

interface Props {
  option: any;
  width?: string;
  height?: string;
  eventHandlers?: EChartEventHandler[];
}

const props = defineProps<Props>();
const chartDom = ref(null);

let myChart: any;

onMounted(() => {
  // Initialize the echarts instance based on the prepared dom
  myChart = echarts.init(chartDom.value!);
  window.addEventListener('resize', myChart.resize as any);

  // Display the chart using the configuration items and data just specified.
  myChart.setOption(props.option);

  // Sets all event handlers on chart.
  setChartEventHandlers();
});

onUnmounted(() => {
  window.removeEventListener('resize', myChart.resize as any);
  myChart?.dispose();
});

watch(props, () => {
  if (myChart == null) {
    // Initialize the echarts instance based on the prepared dom
    myChart = echarts.init(chartDom.value!);
  }

  // Display the chart using the configuration items and data just specified.
  myChart.setOption(props.option);

  // Sets all event handlers on chart.
  setChartEventHandlers();
});

/**
 * Sets all event handlers on chart.
 */
function setChartEventHandlers(): void {
  if (props.eventHandlers) {
    for (const p of props.eventHandlers) {
      myChart.on(p.eventName, p.query, p.handler);
    }
  }
}
</script>

<template>
  <div
    ref="chartDom"
    :style="{
      width: width ?? '1000px',
      height: height ?? '600px',
    }"
  ></div>
</template>

<style scoped></style>
